import {
  createRouter,
  createWebHistory
} from "vue-router";

const routes = [
  {
    path: "/",
    component: () => import("@/Home.vue")
  },
  {
    path: "/admin",
    component: () => import("@/Admin.vue")
  },
  {
    path: "/reg",
    component: () => import("@/Register.vue")
  },
  {
    path: "/location/:vehicleNo/:lon/:lat",
    component: () => import("@/CurrentLocation.vue")
  },
  {
    path: "/map/:vehicleNo/:xc/:mintime/:maxtime",
    component: () => import("@/Map.vue")
  },
  {
    path: "/login",
    component: () => import("@/Login.vue")
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  // 根据token判断是否登录 并且判断token是否过期
  if (localStorage["userToken"] === "fake-tokena") {
      // 登录了就不允许回到login页面
      if (to.path == '/login') {
      // 返回到login页面就会强制跳转到首页
          next({ path: '/' })
      } else {
      // 没有强制跳转到login页面就放行
          next()
      }
  } else {
      // 未登录
      // 判断路径
      if (to.path === '/login' || to.path == '/reg') {
          // 如果本来就在login页面就放行
          next()
      } else {
          // 如果不在login页面就放行到login页面
          next({ path: '/login', query: { redirect: to.path } })
      }
  }
});

export default router;